package yx.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import yx.model.BsStudent;
import yx.service.CorporationServiceInt;
import yx.service.StudentServiceInt;
import yx.utils.ExcelUtils;
import yx.vo.ArchiveVO;
import yx.vo.CorporationVO;
import yx.vo.DatagridVO;
import yx.vo.JsonVO;
import yx.vo.StudentVO;

import com.opensymphony.xwork2.ModelDriven;

@ParentPackage("basePackage")
@Namespace("/")
@Action(value = "studentAction")
public class StudentAction extends BaseAction implements ModelDriven<StudentVO> {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(StudentAction.class);

	private StudentVO student = new StudentVO();

	@Override
	public StudentVO getModel() {
		return student;
	}

	private StudentServiceInt studentService;
	private CorporationServiceInt corporationService;

	public StudentServiceInt getStudentService() {
		return studentService;
	}

	@Autowired
	public void setStudentService(StudentServiceInt studentService) {
		this.studentService = studentService;
	}

	public void queryStudent() {
		super.writeJson(studentService.datagrid(student));
	}

	public CorporationServiceInt getCorporationService() {
		return corporationService;
	}

	@Autowired
	public void setCorporationService(CorporationServiceInt corporationService) {
		this.corporationService = corporationService;
	}

	public void addStudent() {
		// 查询学号是否存在
		StudentVO tempStudent = new StudentVO();
		tempStudent.setStudentNo(student.getStudentNo());
		DatagridVO datagrid = studentService.datagrid(tempStudent);
		if (datagrid.getTotal().intValue() > 0) {
			JsonVO j = new JsonVO();
			j.setSuccess(false);
			j.setMsg("学号已经存在，请重新输入！");
			super.writeJson(j);
		} else {
			JsonVO j = new JsonVO();
			try {
				StudentVO u = studentService.save(student);
				j.setSuccess(true);
				j.setMsg("增加成功！");
				j.setObj(u);
			} catch (Exception e) {
				j.setMsg(e.getMessage());
			}
			super.writeJson(j);
		}
	}

	public void removeStudent() {
		studentService.remove(student.getIds());
		JsonVO j = new JsonVO();
		j.setSuccess(true);
		j.setMsg("删除成功！");
		super.writeJson(j);
	}

	public void editStudent() {
		JsonVO j = new JsonVO();
		try {
			StudentVO u = studentService.edit(student);
			j.setSuccess(true);
			j.setMsg("编辑成功！");
			j.setObj(u);
		} catch (Exception e) {
			j.setMsg(e.getMessage());
		}
		super.writeJson(j);
	}

	public void importStudent() {
		JsonVO j = new JsonVO();
		try {
			// 第一步：读取预置的模板
			String templatePath = ServletActionContext.getServletContext().getRealPath("/") + "template\\StudentImport.xlsx";
			Map<Integer, Boolean> mapCell = ExcelUtils.resolveExcelTemplate(templatePath);
			InputStream inp = new FileInputStream(student.getImportStudent());
			XSSFWorkbook wb = new XSSFWorkbook(inp);
			int countCell = mapCell.size(); // 模板 列数
			List<BsStudent> importStudentList = new ArrayList<BsStudent>();
			// 导入列里 已经存在的 用户编码 集合 K用户编码 V所在Excel中第几行
			Map<String, Integer> importStudentMap = new HashMap<String, Integer>();
			XSSFSheet sheet = wb.getSheetAt(0); // 只 读取 第一个 sheet
			if (sheet.getLastRowNum() == 0) {
				throw new Exception("导入文件中数据不存在！");
			}
			int rownum = sheet.getLastRowNum() + 1;
			XSSFRow row = sheet.getRow(0);
			int cellnum = row.getLastCellNum();
			if (cellnum != countCell) {
				throw new Exception("数据格式和模板不一致！");
			}
			// Key：行号 Value：行的错误ArrayList
			Map<String, List<String>> errorMap = new HashMap<String, List<String>>();

			// 遍历数据行 从 索引为1开始 因为第一行是标题
			for (int index = 1; index < rownum; index++) {
				row = sheet.getRow(index);
				if (row == null || row.getLastCellNum() == 0)
					continue;
				List<String> dataList = new ArrayList<String>();
				List<String> errorList = new ArrayList<String>();
				for (int cellindex = 0; cellindex < cellnum; cellindex++) {
					XSSFCell cell = row.getCell(cellindex);
					String cellStr = ExcelUtils.getExcelCellValue(cell);
					if (mapCell.get(cellindex) && cell == null) {
						errorList.add("第" + (cellindex + 1) + "列不能为空！");
					} else {
						if (cellindex == 1 && cell != null) { // 第二列为学号且不能重复
							if (!importStudentMap.containsKey(cellStr)) {
								StudentVO stuVO = new StudentVO();
								stuVO.setStudentNo(cellStr);
								boolean ret = hasStudent(stuVO);
								if (ret) {
									errorList.add("第" + (cellindex + 1) + "列[学号]已存在！");
								}
								importStudentMap.put(cellStr, cellindex + 1);
							} else {
								errorList.add("第" + (cellindex + 1) + "列[学号]与Excel第" + importStudentMap.get(cellStr) + "行学号相同！");
							}
						}
						if (cellindex == 2 && cell != null) { // 第三列为性别
							if (!cellStr.trim().equals("男") && !cellStr.trim().equals("女")) {
								errorList.add("第" + (cellindex + 1) + "列[性别]只能为男或女！");
							}
						}
						if (cellindex == 4 && cell != null) { // 第五列为工作单位
							CorporationVO corpVO = new CorporationVO();
							corpVO.setCorporationName(cellStr);
							CorporationVO c = hasCorporation(corpVO);
							if (c == null) {
								errorList.add("第" + (cellindex + 1) + "列[工作单位]不存在！");
								cellStr = null;
							} else {
								cellStr = c.getId().toString();
							}
						}
					}
					dataList.add(cellStr);
					errorMap.put((index + 1) + "", errorList);
				}

				StringBuffer rowErrMsgSb = new StringBuffer("");
				List<String> tempList = errorMap.get((index + 1) + "");
				if (tempList != null) {
					for (int n = 0; n < tempList.size(); n++) {
						String str = (String) tempList.get(n);
						rowErrMsgSb.append(str);
					}
				}

				// 判断当前行是否有错
				if ("".equals(rowErrMsgSb.toString())) {
					BsStudent importStudent = new BsStudent();
					importStudent.setStudentName(dataList.get(0));
					importStudent.setStudentNo(dataList.get(1));
					importStudent.setGender("男".equals(dataList.get(2).trim()) ? "01" : "02");
					importStudent.setTitle(dataList.get(3));
					importStudent.setCorporationId(Integer.valueOf(dataList.get(4)));
					importStudent.setPosition(dataList.get(5));
					importStudent.setMobile(dataList.get(6));
					importStudent.setEmail(dataList.get(7));
					importStudent.setQq(dataList.get(8));
					importStudent.setPhone(dataList.get(9));
					importStudent.setFax(dataList.get(10));
					importStudentList.add(importStudent);
				}
			}

			// 判断是否有错
			StringBuffer tempErrMsg = new StringBuffer("");
			for (int ind = 1; ind <= rownum; ind++) {
				List<String> tempList = errorMap.get(ind + "");
				if (tempList != null) {
					for (int t = 0; t < tempList.size(); t++) {
						String str = (String) tempList.get(t);
						tempErrMsg.append(str);
					}
				}
			}

			// 出错处理
			StringBuffer allErrMsg = new StringBuffer("");
			if (!"".equals(tempErrMsg.toString())) {
				for (int ind = 1; ind <= rownum; ind++) {
					List<String> errList = errorMap.get(ind + "");
					String tempErr = "";
					if (errList == null || errList.size() == 0) {
						// 无错
						continue;
					} else {
						StringBuffer sb = new StringBuffer();
						sb.append("第" + ind + "行：");
						java.util.Iterator it = (java.util.Iterator) errList.iterator();
						while (it.hasNext()) {
							String item = (String) it.next();
							sb.append(item + ",");
						}
						tempErr = sb.toString().substring(0, sb.toString().length() - 1) + "\\n";
					}
					allErrMsg.append(tempErr);
				}
				throw new Exception(allErrMsg.toString());
			} else {
				studentService.saveAll(importStudentList);
				j.setSuccess(true);
				j.setMsg("导入成功！");
				super.writeJson(j);
			}
		} catch (Exception e) {
			j.setMsg(e.getMessage());
			super.writeJson(j);
		}
	}

	public void downloadTemplate() {
		OutputStream os = null;
		byte[] bytes = null;
		try {
			String downloadPath = ServletActionContext.getServletContext().getRealPath("/") + "template\\StudentImport.xlsx";
			bytes = studentService.getFileBytes(downloadPath);
			ServletActionContext.getResponse().reset();
			ServletActionContext.getResponse().setCharacterEncoding("utf-8");
			ServletActionContext.getResponse().setHeader("Content-Type", "application/octet-stream");
			ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment; filename=StudentImport.xlsx");
			os = ServletActionContext.getResponse().getOutputStream();
			if (bytes != null) {
				os.write(bytes);
				os.flush();
				os.close();
			}
			logger.info("文档下载成功！");
		} catch (Exception e) {
			logger.error("文档下载失败！");
		} finally {
			try {
				if (bytes != null) {
					os.write(bytes);
					os.flush();
				}
				os.close();
			} catch (IOException e) {
				logger.error("流文件关闭异常！");
			}
		}
	}

	private boolean hasStudent(StudentVO stu) {
		DatagridVO vo = studentService.datagrid(stu);
		if (vo.getTotal() > 0) {
			return true;
		}
		return false;
	}

	private CorporationVO hasCorporation(CorporationVO corp) {
		DatagridVO vo = corporationService.datagrid(corp);
		if (vo.getTotal() > 0) {
			CorporationVO corpVO = (CorporationVO) vo.getRows().get(0);
			return corpVO;
		}
		return null;
	}

}
